package celiasoft.itasalib.filegatherer;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.w3c.dom.Document;

import android.util.Log;
import celiasoft.itasalib.filegatherer.cache.FileCache;
import celiasoft.itasalib.filegatherer.cache.filter.IFileCacheFilter;

public class HTMLGatherer implements IGatherer{

	private final static String TAG = "itasalib.HTMLGatherer";
	private FileCache _cache;
	private boolean _cacheResult = true;

	public HTMLGatherer(FileCache cache) {
		this._cache = cache;
	}

	protected String getFilePath(String url){
		return getFilePath(url,null);
	}
	
	private String getFilePath(String url, IFileCacheFilter filter) {

		String filePath = this._cache.lookup(url);

		if (filePath == null && !this._cacheResult) {

			try {
				URL remoteUrl = new URL(url);
				byte[] stream = FileHTTPFetcher.fetch(remoteUrl);

				if (stream != null){ 
					if(filter == null || filter.cacheIt(stream)) {
						filePath = this._cache.cache(url, stream);
					}
				}
			} catch (IOException ex) {
				ex.printStackTrace();
				Log.e(TAG, "Exception occurred during " + url
						+ " file fetching.");
				return null;
			}
		}

		return filePath;

	}

	public Document getDocument(String url) {
		return null;
	}

	public TagNode getRootNode(String url) {
		TagNode root = null;

		String filePath = getFilePath(url);

		if (filePath == null) {
			Log.d(TAG, "file fetching error");
			return null;
		}

		HtmlCleaner cleaner = new HtmlCleaner();
        try {
			root = cleaner.clean(new File(filePath));
		} catch (IOException e) {
			Log.d(TAG, "I/O exception: " + e.getMessage());
			return null;
		}
		
		return root;
	}

	public void cacheResult(boolean cacheIt) {
		this._cacheResult   = cacheIt;
	}

}
